package C032;

import java.util.HashSet;

/**
 * ClassName: C01
 * Package: C032
 * Description:
 *
 * @Author BCXJ
 * @Create 2024/12/27 20:59
 * @Version 1.0
 * @Since 1.0
 */
public class C01 {
    public static void main(String[] args) {
        int n = 1000;
        int testTimes = 10000;
        System.out.println("测试开始");
        // 实现的位图结构
        BitContainer bitSet = new BitContainer(n);
        // 直接用HashSet做对比测试
        HashSet<Integer> hashSet = new HashSet<>();
        System.out.println("调用阶段开始");
        for (int i = 0; i < testTimes; i++) {
            double decide = Math.random();
            // number -> 0 ~ n-1，等概率得到
            int number = (int) (Math.random() * n);
            if (decide < 0.333) {
                bitSet.add(number);
                hashSet.add(number);
            } else if (decide < 0.666) {
                bitSet.remove(number);
                hashSet.remove(number);
            } else {
                bitSet.reverse(number);
                if (hashSet.contains(number)) {
                    hashSet.remove(number);
                } else {
                    hashSet.add(number);
                }
            }
        }
        System.out.println("调用阶段结束");
        System.out.println("验证阶段开始");
        for (int i = 0; i < n; i++) {
            if (bitSet.contains(i) != hashSet.contains(i)) {
                System.out.println("出错了!");
            }
        }
        System.out.println("验证阶段结束");
        System.out.println("测试结束");
    }


    static class BitContainer {
        int[] bits;


        /**
         * 存取 0 - range -1 的内容
         * @param range
         */
        public BitContainer(int range) {
            bits = new int[range + 31/ 32]; // 需要向上取整
        }

        //：把num加入到位图
        // 0 -> 31 .... 0
        // 1 -> 63 .... 32
        void add(int num) {
            bits[num / 32] |= 1 << (num % 32);
        }

        // ：把num从位图中删除
        void remove(int num) {
            bits[num / 32] &= ~(1 << (num % 32));
        }

        // ：如果位图里没有num，就加入；如果位图里有num，就删除
        void reverse(int num) {
            bits[num / 32] ^= (1 << (num % 32));
        }

        // ：查询num是否在位图中
        boolean contains(int num) {
            return (bits[num / 32] & (1 << (num % 32))) != 0;
        }

    }
}
